/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 *
 * @author JoWooyeon
 */
public class ExternalManager {

    public static void runExternalAPI(String url) throws MalformedURLException{
        openWebpage(new URL(url));
    }
    public static void copyWebPage(String urlPath) {
        URL url = null;
        BufferedReader br = null; // URL정보를 긁어오기 위함
        BufferedWriter bw = null;
        String str = null;

        try {// URL은 프로토콜(http)부터 다 써줘야 한다
            url = new URL("http://java.sun.com");
        } catch (MalformedURLException e) {
            System.out.println("잘못된URL 입니다");
            e.printStackTrace();
        }// URL 객체만 생성하고 통신하고 있는 상태는 아님

        //데이터긁어오기 , 읽을때 파일명이아닌 네트웍 주소를 가져와야함 
        try {
            bw = new BufferedWriter(new FileWriter("sourceCopy.html"));
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            //url.openStream()을 넣으면 네트웍주소를 가져옴
            
            //서버쪽코드에는 접근할수 없고
            //클라이언트쪽에서 보여지는 창의 코드들을 읽어서 출력함 
            //클라이언트쪽 코드도 막아놓을 수도 있음 
            while ((str = br.readLine()) != null) {
                System.out.println(str);
                bw.write(str);
                bw.write("\r\n");
            }
        bw.close();
        br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void openWebpage(URI uri) {
        Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
        if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
            try {
                desktop.browse(uri);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void openWebpage(URL url) {
        try {
            openWebpage(url.toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}


